package org.example.novel.exception;

import org.example.novel.utlis.Result;
import org.example.novel.utlis.IpUtils;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.io.NotActiveException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @Autowired
    HttpServletRequest request;

    public static Logger loggerFactory = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 认证失败异常处理
     * @param authException
     * @return
     */
    @ExceptionHandler(AuthException.class)
    public Result<Boolean> AuthException(AuthException authException){

        String message = authException.getMsg();

        loggerFactory.error(()->"认证异常信息:"+message+",来自Ip:"+IpUtils.getIpAddr());

        return Result.fail(401,message);
    }

    /**
     * 验证码异常处理
     * @param captChaException
     * @return
     */
    @ExceptionHandler(CaptChaException.class)
    public Result<Boolean> CaptChaException(CaptChaException captChaException){

        String message = captChaException.getMsg();

        loggerFactory.error(()->"验证码异常信息:"+message+",来自Ip:"+IpUtils.getIpAddr());

        return Result.fail(401,message);
    }

    /**
     * 业务代码异常处理
     * @param serviceException
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public Result<Boolean> ServiceException(ServiceException serviceException){

        String message = serviceException.getMsg();

        loggerFactory.error(()->"业务异常信息:"+message+",来自Ip:"+IpUtils.getIpAddr());

        return Result.fail(500,message);
    }


    /**
     * 限流异常处理
     * @return
     */
    @ExceptionHandler(RateLimiterException.class)
    public Result<Boolean> Exception(RateLimiterException e){

        String message = e.getMsg();

        loggerFactory.error(()->"限流信息:"+message+",来自Ip:"+IpUtils.getIpAddr());

        return Result.fail(408,message);
    }

    @ExceptionHandler(BindException.class)
    public Result<?> BindException(BindException bindException){
        return Result.fail(bindException.getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public Result<?> noHandlerFoundException(NoHandlerFoundException foundException){
        return Result.fail(404,"页面资源不存在");
    }

}

